package com.jindi.jacococli.api.entrance.listener;

import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.jindi.jacococli.biz.config.ServiceProjectConfig;
import com.jindi.jacococli.biz.constant.Constant;
import com.jindi.jacococli.biz.utils.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApolloConfigListener implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApolloConfigListener.class);

    private ApplicationContext applicationContext;
    @ApolloConfigChangeListener(value = {"application"})
    private void onChange(ConfigChangeEvent changeEvent) {
        for (String key : changeEvent.changedKeys()) {
            if (StringUtils.equals(key, Constant.SERVICE_LIST)) {
                ConfigChange change = changeEvent.getChange(key);
                LOGGER.info("Constant.SERVICE_LIST change, json:{}", JSONUtils.toJSONString(change));
                applicationContext.getBean(ServiceProjectConfig.class).updateProjects(change.getNewValue());
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
